package com.eight.travel.controller;

import com.eight.travel.pojo.Admin;
import com.eight.travel.pojo.User;
import com.eight.travel.service.AdminService;
import com.eight.travel.utils.BaseResp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author Q小旭
 * @version 1.0
 */
@RestController
@RequestMapping("/admin")
@CrossOrigin(origins = "*",allowCredentials = "true")
@Api(value = "通用接口",tags = {"通用接口"})
public class AdminController {

    @Autowired
    AdminService adminService;

    @ApiOperation(value = "管理员登录")
    @PostMapping("/login")
    public BaseResp login(String name,String pass){
        //获得认证主体
        Subject subject = SecurityUtils.getSubject();
        //接受前端的数据
        UsernamePasswordToken token = new UsernamePasswordToken(name, pass);
        //调用登录方法
        subject.login(token );
        return new BaseResp().SUCCESS("登录成功",null,null);
    }

    @ApiOperation(value = "注册管理员")
    @PostMapping("/register")
    public BaseResp register(@RequestBody Admin admin){
        Admin byUname = adminService.findByUname(admin.getAdminname());
        if (byUname != null){
            return new BaseResp().FAIL("已有账号，请登录");
        }
        adminService.saveOrUpdate(admin);
        return new BaseResp().SUCCESS("注册成功",null,null);
    }

    @ApiOperation(value = "分页查询管理员")
    @GetMapping("/findAll")
    public BaseResp findAll(Integer page,Integer size){
        return adminService.findAll(page,size);
    }

    @ApiOperation(value = "删除管理员")
    @DeleteMapping("/deleteById")
    public BaseResp deleteById(@RequestBody Admin admin ){
        return adminService.deleteById(admin);
    }

    @ApiOperation(value = "编辑管理员")
    @PostMapping("/addOrUpdate")
    public BaseResp addOrUpdate(@RequestBody Admin admin ){
        boolean b = adminService.saveOrUpdate(admin);
        if (b == true){
            return new BaseResp().SUCCESS("操作成功",null,null);
        }
        return new BaseResp().FAIL("操作失败");
    }




}
